package User
import (
	"time"
	"strconv"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	"ICan/hook"
	"github.com/gin-gonic/gin"
	"ICan/errmsg"
	"ICan/SDK"
	M "ICan/MySql"
)
type user struct {
	User_id int `json:"user_id"`
	User_phone string `json:"user_phone"`
	Name string `json:"user_name"`
	Pic string `json:"user_pic"`
	Password string `json:"user_password"`
	Email string `json:"user_email"`
}
var idMax user
var yan1 string = "000000"
func insert(i int, a string) (string, int) {
	sqlstr := `insert into user (user_id,user_name,user_phone,user_password,user_pic) values (?, ?, ?, ?, "a")`
	now := time.Now()
	ret, _ := M.Db.Exec(sqlstr, i, now.Unix(), a, "123456")
	id, _ := ret.LastInsertId() //插入的id
	return strconv.FormatInt(now.Unix(),10),int(id)
}
func queryMoer(ctx *gin.Context, p, v string) {  //查
	sqlstr2 := `select user_id from user`
	rows, _ := M.Db.Query(sqlstr2)
	defer rows.Close()
	for  rows.Next() {
		if rows.Next(){
			continue
		}else {
			rows.Scan(&idMax.User_id)
		}
	}
	if (v == yan1){
		name, id := insert(idMax.User_id, p)
		token, _ := hook.SetToken(name)
		code :=  errmsg.Succse
		var us user
		us.User_id=id
		us.Name=name
		us.User_phone=p
		us.Pic="a"
		us.Password="123456"
		data := map[string]interface{}{
			"code":code,
			"msg":errmsg.GetErrMSg(code),
			"data":us,
			"token":token,
		}
		ctx.JSON(http.StatusOK,data)
	}else{
		code := errmsg.Error_ver
		data := map[string]interface{}{
			"code":code,
			"msg":errmsg.GetErrMSg(code),
		}
		ctx.JSON(http.StatusOK,data)
	}

}
func F1(ctx *gin.Context) {
	phone := ctx.PostForm("user_phone")
	ver := ctx.PostForm("verification")
	queryMoer(ctx, phone, ver)
}

func F2(ctx *gin.Context) {
	phone := ctx.PostForm("user_phone")
	sqlstr := `select user_id from user where user_phone = ?`
	rowObj := M.Db.QueryRow(sqlstr, phone)
	var u user
	rowObj.Scan(&u.User_id)
	if u.User_id > 0 {
		code :=  errmsg.Error_phone_ver
		data := map[string]interface{}{
			"code":code,
			"msg":errmsg.GetErrMSg(code),
		}
		ctx.JSON(http.StatusOK,data)
	}else {
		yan1 = SDK.SDK(phone)
		code :=  errmsg.Succse
		data := map[string]interface{}{
			"code":code,
			"msg":errmsg.GetErrMSg(code),
		}
		ctx.JSON(http.StatusOK,data)
	}
}